#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeNodes(ListNode* head) {
        ListNode* prev = head, * pcur = head->next;
        while (pcur != nullptr)
        {
            if (pcur->next == nullptr)
            {
                prev->next = nullptr;
                delete pcur;
                break;
            }
            if (pcur != nullptr && pcur->val != 0)
            {
                prev->val += pcur->val;

                ListNode* tmp = pcur->next;
                delete pcur;
                pcur = tmp;
            }
            else
            {
                prev->next = pcur;
                prev = pcur;
                pcur = pcur->next;
            }
        }
        return head;
    }
};